# @author : sentry
# @since : 2023-09-11
# split算法实现

"""
split()通过指定分隔符对字符串进行切片，如果第二个参数num有指定值，
则分割为num+1个子字符串，返回列表。
string = ‘life-is-short-you-need-python'
string.split('-')
["life","is","short","you","need","python"]
string.split('-',2)
["life","is","short-you-need-python"]
"""


def split_s(string, sep='', num=0):
    split_words = []
    last_index = 0
    # 切割次数
    count = 0

    for index, char in enumerate(string):
        if num > 0 and count == num:
            split_words.append(string[last_index:len(string)])
            break
        if char == sep:
            split_words.append(string[last_index:index])
            # 重置分割符指向下一个位置
            last_index = index + 1
            count += 1
        elif index + 1 == len(string):
            # 最后一个单词判断
            split_words.append(string[last_index:index + 1])
    return split_words


print(split_s("life-is-short-you-need-python", '-'))
# ['life', 'is', 'short', 'you', 'need', 'python']

print(split_s("life-is-short-you-need-python", '-', 2))
# ['life', 'is', 'short-you-need-python']
